package com.qingke.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxParserHandler extends DefaultHandler{
	private String nodeName = null;
	private static List<Map<String,String>> list = null;
	private Map<String,String> map = null;
	private String currentTag = null;
	private String currentValue = null;
	
	
	public SaxParserHandler(String name){
		nodeName = name;
	}
	
	public void startDocument() throws SAXException{
		list = new ArrayList<Map<String,String>>();
	}
	
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
		if(qName.equals(nodeName))
			map = new HashMap<String,String>();
		
		if(map != null && attributes != null){
			for(int i = 0;i<attributes.getLength();i++){
				map.put(attributes.getQName(i), attributes.getValue(i));
			}
		}
		
		currentTag = qName;
	}
	
	public void characters (char ch[], int start, int length) throws SAXException{
		if(map != null && currentTag != null)
			currentValue = new String(ch,start,length);
		if(currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("\n"))
			map.put(currentTag, currentValue);
		
		currentTag = null;
		currentValue = null;
	}
	
	public void endElement (String uri, String localName, String qName){
		if(qName.equals(nodeName)){
			list.add(map);
			map = null;
		}
	}
	
	  public void endDocument() throws SAXException{
		      super.endDocument();
	}
	  
	  public static List<Map<String,String>> getList(){
		  return list;
	  }
}
